//
//  ZJMineViewController.m
//  ZiJinLian
//
//  Created by lzy on 2017/3/10.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "ZJMineViewController.h"
#import "ZJDeliveryAddressViewController.h"
#import "ZJBaseNavControllerViewController.h"
#import "ZJLoginViewController.h"
#import "ZJMineMessageController.h"
#import "ZJMineSetController.h"
#import "ZJMeModel.h"
#import "ZJMeCell.h"
#import "MyWalletViewController.h"
#import "MyWishViewController.h"
#import "MyOrderViewController.h"
#import "MessageViewController.h"
#import "MyOrderListViewController.h"
#import "AllOrderViewController.h"
#import "SalesViewController.h"
#import "ExclusiveViewController.h"
#import "AboutUSViewController.h"
#import "MineDataViewController.h"

@interface ZJMineViewController ()<UITableViewDelegate,UITableViewDataSource,ZJMeHeadViewDelegate>
@property (nonatomic, strong) UIImage  * itemImage;

@property (nonatomic,strong)NSMutableArray *sec1Arr;
@property (nonatomic,strong)NSMutableArray *sec2Arr;
@property (nonatomic,strong)NSMutableArray *sec3Arr;
@end

@implementation ZJMineViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
     _isLogin=[ZJUserDefaultsTools isLogin];
    self.navigationController.navigationBar.hidden=NO;
    [self setupUnreadMessageCount];
    [(ZJBaseNavControllerViewController*)self.navigationController hideNav];
    if (_isLogin) {
        [_headView.headImg sd_setImageWithURL:[NSURL URLWithString:[ZJUserDefaultsTools getAvatar]]];
    }else{
        [_headView.headImg setImage:[UIImage imageNamed:@"img_head_nor"]];
    }
    [_headView.headView setTitle:_isLogin?[ZJUserDefaultsTools getCurrentNickName]:DEFAULT_NICKNAME forState:UIControlStateNormal];
    self.isShowDiag=NO;
    [self loadOrderCount];
    //[self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}


-(void)createView{
    [self createData];
    [self createNav];
	self.view.backgroundColor = RGB(246, 246, 246);
	
    _headView=[[ZJMeHeadView alloc]initWithFrame:CGRectMake(0, 0, screen_Width, 180+50+MainW/4)];
    //_headView.headView.userInteractionEnabled=YES;
    _headView.headView.imageView.bsg_width=50;
    _headView.headView.imageView.bsg_height=50;
    _headView.headImg.layer.cornerRadius=25;
    _headView.headImg.layer.masksToBounds=YES;
    _headView.delegate=self;
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH-49) style:UITableViewStyleGrouped];
    
    [self.view addSubview:_tableView];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    //_tableView.backgroundColor=[UIColor clearColor];
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.separatorInset=UIEdgeInsetsMake(0, 0, 0, 0);
    _tableView.separatorColor=SeparatorColor;
    _tableView.separatorInset=UIEdgeInsetsZero;
	_tableView.backgroundColor = RGB(246, 246, 246);
    MJRefreshNormalHeader*header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopic)];
//    header.stateLabel.textColor=[UIColor whiteColor];
//    header.lastUpdatedTimeLabel.textColor = [UIColor whiteColor];
    _tableView.mj_header=header;
	
	_tableView.tableHeaderView = _headView;
     [LoadMaskHelper showMaskWithType:StockTimesharing onView:self.view delay:0.01];
   
}
//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    return _headView;
//
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//
//
//    return 180+50+MainW/4;
//}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return section == 0 ? 0.01:8;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
	return 0.01;
}

-(void)createData{
    ZJMeModel* mode1=[[ZJMeModel alloc]initWithTitle:MyString(@"我的心愿") icon:@"icon_my_wish"];
    ZJMeModel* mode2=[[ZJMeModel alloc]initWithTitle:MyString(@"我的收藏") icon:@"icon_collect"];
     ZJMeModel* mode7=[[ZJMeModel alloc]initWithTitle:MyString(@"我的专享") icon:@"icon_exclusive"];
    ZJMeModel* mode3=[[ZJMeModel alloc]initWithTitle:MyString(@"我的钱包") icon:@"icon_wallet1"];
    ZJMeModel* mode4=[[ZJMeModel alloc]initWithTitle:MyString(@"我的供养") icon:@"icon_fend1"];
    ZJMeModel* mode5=[[ZJMeModel alloc]initWithTitle:MyString(@"收货地址管理") icon:@"icon_address"];
    ZJMeModel* mode6=[[ZJMeModel alloc]initWithTitle:MyString(@"关于我们") icon:@"icon_us"];
	ZJMeModel *mode8 = [[ZJMeModel alloc]initWithTitle:MyString(@"加盟合作") icon:@"icon_cooperation"];
    _data=[[NSMutableArray alloc]init];
    [_data addObject:mode1];
    [_data addObject:mode2];
    [_data addObject:mode7];
    [_data addObject:mode3];
    [_data addObject:mode4];
    [_data addObject:mode5];
    [_data addObject:mode6];
	[_data addObject:mode8];
	self.sec1Arr = [NSMutableArray array];
	self.sec2Arr = [NSMutableArray array];
	self.sec3Arr = [NSMutableArray array];
	
	[self.sec1Arr addObject:mode1];
	[self.sec1Arr addObject:mode2];
	[self.sec1Arr addObject:mode4];
	[self.sec1Arr addObject:mode7];
	
	[self.sec2Arr addObject:mode5];
	[self.sec2Arr addObject:mode3];
	
	[self.sec3Arr addObject:mode6];
	[self.sec3Arr addObject:mode8];
	
}

-(void)doOpeartion{

   
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2 && indexPath.row == 0) {
        NSLog(@"关于我们");
        AboutUSViewController*vc=[[AboutUSViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
	}else if (indexPath.section == 2 && indexPath.row == 1){
		WelcomViewController*vc=[[WelcomViewController alloc]init];
		vc.reLastURL=@"https://www.zjlwh.net/cooperation.html";
		[self.navigationController pushViewController:vc animated:YES];
	}else{
        if (_isLogin) {
			if (indexPath.section == 0) {
				switch (indexPath.row) {
					case 0:
						//心愿
					{
						MyWishViewController*vc=[[MyWishViewController alloc]init];
						vc.popWhere=1;
						[self.navigationController pushViewController:vc animated:YES];
					}
						break;
					case 1:
						//收藏
					{
						MyOrderViewController*vc=[[MyOrderViewController alloc]init];
						[self.navigationController pushViewController:vc animated:YES];
					}
						break;
					case 2:
						//我的供养
					{
						[self showToast:MyString(@"未开放")];

					}
						break;
					case 3:
						//我的专享
					{
						ExclusiveViewController*vc=[[ExclusiveViewController alloc]init];
						[self.navigationController pushViewController:vc animated:YES];
					}
						break;
					default:
						break;
				}
				
				
			}else if (indexPath.section == 1){
				switch (indexPath.row) {
					case 0:
						//收获地址管理
					{
						[self goDeliveryClick];

					}
						break;
					case 1:
						//我的钱包
					{
						MyWalletViewController *vc=[[MyWalletViewController alloc]init];
						[self.navigationController pushViewController:vc animated:YES];
					}
					default:
						break;
				}
				
			}

			/*
            switch (indexPath.row) {
                case 0:{
                   // [self showToast:MyString(@"未开放")];
                    MyWishViewController*vc=[[MyWishViewController alloc]init];
                    vc.popWhere=1;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    //心愿
                    break;
                case 1:{
                    MyOrderViewController*vc=[[MyOrderViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    //收藏
                    break;
                case 2:{
                    ExclusiveViewController*vc=[[ExclusiveViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    //收藏
                    break;
                case 3:{
                    //钱包
                    //[self showToast:@"暂未开放!"];
                    MyWalletViewController *vc=[[MyWalletViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    
                    break;
                case 4:
                    //供养
                    [self showToast:MyString(@"未开放")];
                    break;
                case 5:
                    //地址
                    [self goDeliveryClick];
                    break;
                case 6:
                    //关于我们
                    [self showToast:MyString(@"未开放")];
                    break;
                case 7:
					//加盟合作
				{
					NSLog(@"加盟合作");
					//https://www.zjlwh.net/cooperation.html
					WelcomViewController*vc=[[WelcomViewController alloc]init];
					vc.reLastURL=@"https://www.zjlwh.net/cooperation.html";
					[self.navigationController pushViewController:vc animated:YES];
				}
					break;
				
                default:
                    break;
            }
			 */

        }else{
            ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
            ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
            controller.modality=NO;
            [self presentViewController:nav animated:YES completion:nil];
        }
  
    }
    
    
   
   
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return  3;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 
//    return _data.count;
	if (section == 0) {
		return 4;
	}else
		return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 50;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static  NSString* ID=@"cell";
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    if (_data[indexPath.row]!=nil) {
		
//        ZJMeModel* model= _data[indexPath.row];
		ZJMeModel *model;
		if (indexPath.section == 0) {
			model = self.sec1Arr[indexPath.row];
		}else if (indexPath.section == 1){
			model = self.sec2Arr[indexPath.row];
		}else{
			model = self.sec3Arr[indexPath.row];
		}
		
        cell.imageView.image=[UIImage imageNamed:model.icon];
        cell.textLabel.font=FontAndStyle14;
        cell.textLabel.textColor=TextColor3;
        cell.textLabel.text=model.title;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}







#pragma mark 创建导航栏
-(void)createNav{
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [settingBtn addTarget:self action:@selector(dosettingAction:) forControlEvents:UIControlEventTouchUpInside];
    [settingBtn setTitle:MyString(@"设置") forState:UIControlStateNormal];
    settingBtn.titleLabel.font = FontAndStyle14;
    [settingBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [settingBtn setFrame:CGRectMake(0, 0, 44, 44)];
    UIBarButtonItem *settingItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
    self.navigationItem.leftBarButtonItems = @[negativeSpacer,settingItem];
    self.itemImage= [UIImage imageNamed:@"icon_message_nor"];
    self.itemImage = [self.itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:self.itemImage style:UIBarButtonItemStylePlain target:self action:@selector(messageClick:)];
    self.navigationItem.rightBarButtonItem =rightBarButtonItem;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction) name:@"unReadInfo" object:nil];
   

    //右边
    //[ZJNavTool rightItemOnNavigationItem:self target:self action:@selector(messageClick:) andType:item_message];
}
-(void)InfoNotificationAction{
    self.itemImage= [UIImage imageNamed:@"icon_message_reminder"];
    self.itemImage = [self.itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:self.itemImage style:UIBarButtonItemStylePlain target:self action:@selector(messageClick:)];
    self.navigationItem.rightBarButtonItem =rightBarButtonItem;
}

#pragma mark 头像点击

-(void)headClickOption{
    if (_isLogin) {
        MineDataViewController* con=[[MineDataViewController alloc]init];
        [self.navigationController pushViewController:con animated:YES];
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }
}


#pragma mark 设置
-(void)dosettingAction:(UIButton *)btn
{
    if (_isLogin) {
        ZJMineSetController *vc=[[ZJMineSetController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }

}


#pragma -----------------------消息按钮的点击方法------------------------------
-(void)messageClick:(UIButton *)btn
{
    if (_isLogin) {
        EaseConversationListViewController *chatController = [[EaseConversationListViewController alloc]init];
        chatController.title=MyString(@"消息");
        [self.navigationController pushViewController:chatController animated:YES];
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }
    
}

#pragma mark 去地址管理
-(void)goDeliveryClick
{
    if (_isLogin) {
        ZJDeliveryAddressViewController *adressVC=[[ZJDeliveryAddressViewController alloc]init];
        [self.navigationController pushViewController:adressVC animated:YES];
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }
}
#pragma mark -------订单状态
//待付款
-(void)obligationClick:(ZJTipsBtn *)sender{
    if (_isLogin) {
        if (sender.tag==4) {
            MyOrderListViewController *vc=[[MyOrderListViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            AllOrderViewController *vc=[[AllOrderViewController alloc]init];
            vc.stype=sender.tag;
            [self.navigationController pushViewController:vc animated:YES];
        }

    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }
    
    
}
-(void)allorderClick{
    if (_isLogin) {
        AllOrderViewController *vc=[[AllOrderViewController alloc]init];
        vc.stype=0;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }

    

}
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    NSLog(@"未读消息%ld",(long)unreadCount);
    if (unreadCount>0) {
        NSNotification *notification =[NSNotification notificationWithName:@"unReadInfo" object:nil userInfo:nil];
        // 3.通过 通知中心 发送 通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }else{
        self.itemImage=[UIImage imageNamed:@"icon_message_nor"];
        self.itemImage = [self.itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIBarButtonItem *rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:self.itemImage style:UIBarButtonItemStylePlain target:self action:@selector(messageClick:)];
        self.navigationItem.rightBarButtonItem =rightBarButtonItem;
    }
    
}
-(void)loadOrderCount{
    if (!_isLogin) {
        [_headView.waitPayBtn hideTips:YES];
        [_headView.waitSend hideTips:YES];
        [_headView.waitRev hideTips:YES];
        [_headView.waitQuit hideTips:YES];
        return;
    }else{
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
        [self doHttpRequestWithApi:API_ORDERCOUNT method:GET dic:dic successBlock:^(NSDictionary *dic) {
            if ([dic[@"data"][@"10"] intValue]!=0) {
                [_headView.waitPayBtn addNumber:[NSString stringWithFormat:@"%@",dic[@"data"][@"10"]]];
            }else{
                [_headView.waitPayBtn hideTips:YES];
            }
            if ([dic[@"data"][@"80"] intValue]!=0){
                 [_headView.waitSend addNumber:[NSString stringWithFormat:@"%@",dic[@"data"][@"80"]]];
            }else{
                [_headView.waitSend hideTips:YES];
            }
            if ([dic[@"data"][@"90"] intValue]!=0){
                [_headView.waitRev addNumber:[NSString stringWithFormat:@"%@",dic[@"data"][@"90"]]];
            }else{
                [_headView.waitRev hideTips:YES];
            }
            if ([dic[@"data"][@"9"] intValue]!=0){
                [_headView.waitQuit addNumber:[NSString stringWithFormat:@"%@",dic[@"data"][@"9"]]];
            }else{
                [_headView.waitQuit hideTips:YES];
            }
            [_tableView.mj_header endRefreshing];
            NSLog(@"数据怎么样:%@",dic);
        }];
    }
}
-(void)loadNewTopic{
    if (_isLogin) {
        [self loadOrderCount];
    }else{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_header endRefreshing];
        });
    }
}

@end
